/*
 * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.io;

/**
 * Context during upcalls from object stream to class-defined
 * readObject/writeObject methods.
 * 从对象流到类定义的readObject/writeObject方法的调用期间的上下文
 * Holds object currently being deserialized and descriptor for current class.
 * 保存当前正在序列化对象以及当前类的描述符
 * This context keeps track of the thread it was constructed on, and allows
 * only a single call of defaultReadObject, readFields, defaultWriteObject
 * or writeFields which must be invoked on the same thread before the class's
 * readObject/writeObject method has returned.
 * 当前上下文会跟踪构造它的线程,并且只允许对defaultReadObject,readFields,defaultWriteObject或者wrtieFields进行一次调用。
 * 在类的readObject/wrtieObject方法返回之前,必须在同一线程上调用这些函数。
 * If not set to the current thread, the getObj method throws NotActiveException.
 * 如果没有设置当前线程,getObj方法会抛出NotActiveException
 */
final class SerialCallbackContext {
    //
    private final Object obj;
    //
    private final ObjectStreamClass desc;
    /**
     * Thread this context is in use by.
     * As this only works in one thread, we do not need to worry about thread-safety.
     * 线程正在使用这个上下文
     * 由于这个只适用于一个线程,因此我们不需要担心线程安全性问题
     * 构造SerialCallbackContext后,就会跟踪构造者的线程
     */
    private Thread thread;

    public SerialCallbackContext(Object obj, ObjectStreamClass desc) {
        this.obj = obj;
        this.desc = desc;
        this.thread = Thread.currentThread();
    }
    //CAS
    public Object getObj() throws NotActiveException {
        checkAndSetUsed();
        return obj;
    }

    public ObjectStreamClass getDesc() {
        return desc;
    }

    public void check() throws NotActiveException {
        // 同样是CAS
        if (thread != null && thread != Thread.currentThread()) {
            throw new NotActiveException(
                "expected thread: " + thread + ", but got: " + Thread.currentThread());
        }
    }

    private void checkAndSetUsed() throws NotActiveException {
        // 如果操作前后的线程不同,证明已经不在同一个readObject方法里调用了
        if (thread != Thread.currentThread()) {
            // 不在readObject调用或已读取的字段中
             throw new NotActiveException(
              "not in readObject invocation or fields already read");
        }
        thread = null; // 使用完了,只能一次使用
    }
    // thread为null 也就是使用完了
    public void setUsed() {
        thread = null;
    }
}
